package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw.step.HealthyConfig;
import com.shwread.android.qysw.step.adapter.ChooseFriendAdapter;
import com.shwread.android.qysw.step.adapter.RankAdapter;
import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.api.MyNoLoadAsynctask;
import com.shwread.android.qysw.step.dto.HMFriend;
import com.shwread.android.qysw.step.dto.HMFriendsDto;
import com.shwread.android.qysw.step.dto.HMRank;
import com.shwread.android.qysw.step.dto.HMRankDto;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.LoadMoreListView;
import com.shwread.android.qysw.tools.TimeHelper;
import com.shwread.android.qysw10000136.R;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.sharesdk.framework.ShareSDK;
import logic.constants.AppConfig;

/**
 * Created by Fantasy on 16/4/2.
 */
public class HealthyChooseFriendActivity extends Activity {
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.all_choose_btn)
    TextView allChooseBtn;
    @InjectView(R.id.friend_listview)
    LoadMoreListView friendListview;
    @InjectView(R.id.choose_num_text)
    TextView chooseNumText;
    @InjectView(R.id.sure_button)
    RelativeLayout sureButton;
    @InjectView(R.id.tweleve_text)
    TextView tweleveText;
    private LinearLayoutManager linearLayoutManager;
    public ChooseFriendAdapter chooseFriendAdapter;

    public ArrayList<Map<String, Integer>> chooseList;
    private List<Object> mAllPersonList;
    public String mGameType;//1：好友比赛，2：组团赛，3：竞赛

    public String mMatchException = "";//比赛说明
    public String mMatchName = "";//比赛名称
    public String mPlayers = "";//1,2,3
    public String mStartTime = "";
    public String mEndTime = "";
    public String mTargetStep = "";

    int choosePlayerNum = 0;
    boolean isAllChoose = false;

    private boolean isHasMore = true;
    private int mPage = 1;
    private boolean isLoading = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.healthy_choose_friend);
        ButterKnife.inject(this);
        titleText.setText("选择好友");
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        linearLayoutManager = new LinearLayoutManager(this);
        friendListview.setLayoutManager(linearLayoutManager);

        mAllPersonList = new ArrayList<>();
        chooseList = new ArrayList<>();
        chooseFriendAdapter = new ChooseFriendAdapter(HealthyChooseFriendActivity.this, new ChooseFriendAdapter.MyCallBack() {
            @Override
            public void chooseSuccess(int userId, int isChoose) {
                Log.i("darren", "userId:" + userId + "   isChoose:" + isChoose);
                for (int i = 0; i < chooseList.size(); i++) {
                    if (chooseList.get(i).get("userId") == userId) {
                        chooseList.get(i).put("isChoose", isChoose);
                    }
                }
                choosePlayerNum = 0;
                for (int j = 0; j < chooseList.size(); j++) {
                    if (chooseList.get(j).get("isChoose") == 1) {
                        choosePlayerNum++;
                    }
                }
//                            if (choosePlayerNum > 10 && !mGameType.equals("1")) {
//                                chooseNumText.setTextColor(getResources().getColor(R.color.red_d0));
//                                chooseNumText.setText("不能再添加人数");
//                            } else {
                chooseNumText.setTextColor(getResources().getColor(R.color.white));
                chooseNumText.setText("确定(已选择" + choosePlayerNum + "人)");
                //  }

            }
        });
        chooseFriendAdapter.init_data_list(mAllPersonList);
        friendListview.setLoadMoreListViewAdapter(chooseFriendAdapter);
        friendListview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = linearLayoutManager.getItemCount();
                Log.i("darren", "totalItemCount:" + totalItemCount);
                if (lastVisibleItem >= totalItemCount - 4 && dy >= 0 && isHasMore) {
                    refreshData(mPage);
                } else if (mAllPersonList.size() < 4 && isHasMore) {
                    refreshData(mPage);
                }
            }
        });
        isLoading = false;

        chooseNumText.setText("确定(已选择" + choosePlayerNum + "人)");
        Intent intent = getIntent();
        mMatchName = intent.getStringExtra("matchName");
        mMatchException = intent.getStringExtra("matchException");
        mStartTime = intent.getStringExtra("startTime");
        mEndTime = intent.getStringExtra("endTime");
        mTargetStep = intent.getStringExtra("targetStep");
        mGameType = intent.getStringExtra("gameType");
        allChooseBtn.setVisibility(View.VISIBLE);
//        if (mGameType.equals("1")) {
//            allChooseBtn.setVisibility(View.VISIBLE);
//        } else {
//            allChooseBtn.setVisibility(View.INVISIBLE);
//        }
        Log.i("darren", "mMatchName:" + mMatchName);
        Log.i("darren", "mMatchException:" + mMatchException);
        Log.i("darren", "mStartTime:" + mStartTime);
        Log.i("darren", "mEndTime:" + mEndTime);
        Log.i("darren", "mTargetStep:" + mTargetStep);
        Log.i("darren", "mGameType:" + mGameType);
        if (!mGameType.equals("1")) {
            tweleveText.setVisibility(View.INVISIBLE);
        }

        allChooseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chooseList != null) {
                    if (!isAllChoose) {
                        for (int i = 0; i < chooseList.size(); i++) {
                            chooseList.get(i).put("isChoose", 1);
                            isAllChoose = true;
                            allChooseBtn.setText("取消");
                        }
                        chooseFriendAdapter.notifyDataSetChanged();
                        choosePlayerNum = chooseList.size();
                        chooseNumText.setText("确定(已选择" + chooseList.size() + "人)");
                    } else {
                        for (int i = 0; i < chooseList.size(); i++) {
                            chooseList.get(i).put("isChoose", 0);
                            isAllChoose = false;
                            allChooseBtn.setText("全选");
                        }
                        chooseFriendAdapter.notifyDataSetChanged();
                        choosePlayerNum=0;
                        chooseNumText.setText("确定(已选择0人)");
                    }

                }
            }
        });


        sureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayers="";
                if (choosePlayerNum == 0) {
                    Toast.makeText(HealthyChooseFriendActivity.this, "请选择好友", Toast.LENGTH_SHORT).show();
                } else {
                    HashMap<String, String> createParams = new HashMap<>();
                    createParams.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
                    createParams.put("enterpriseId", AppConfig.getEnterpriseId());
                    if ("1".equals(mGameType)) {//友谊赛
                        mStartTime = TimeHelper.getMyFriendPKStart() + "";
                        mEndTime = TimeHelper.getMyFriendPKEnd(TimeHelper.getMyFriendPKStart()) + "";
                        Log.i("darren", mStartTime);
                        Log.i("darren", mEndTime);
                    } else if ("2".equals(mGameType)) {//组团赛

                    } else if ("3.".equals(mGameType)) {//竞赛

                    }
                    for (int i = 0; i < chooseList.size(); i++) {
                        if (chooseList.get(i).get("isChoose") == 1) {
                            mPlayers = mPlayers + chooseList.get(i).get("userId") + ",";
                        }
                    }
                    Log.i("darren", "beforePlayers" + mPlayers);
                    if (!TextUtils.isEmpty(mPlayers)) {
                        mPlayers = mPlayers.substring(0, mPlayers.length() - 1);
                        Log.i("darren", "mPlayers:" + mPlayers);
                    }


                    createParams.put("startTime", mStartTime);
                    createParams.put("endTime", mEndTime);

                    if (mGameType.equals("3")) {
                        createParams.put("targetStep", mTargetStep);
                    }
                    if (mGameType.equals("3") || mGameType.equals("2")) {
                        createParams.put("matchName", mMatchName);
                        createParams.put("matchExplain", mMatchException);
                    }

                    createParams.put("type", mGameType);
                    createParams.put("players", mPlayers);
                    String createUrl = "/hzlqswserver/health/game/create";
                    HashMap<String, String> hashMapCreateUrl = new HashMap<>();
                    hashMapCreateUrl.put("url", createUrl);
                    MyAsynctask asynctask = new MyAsynctask(HealthyChooseFriendActivity.this, new MyAsynctask.RequestListener() {
                        @Override
                        public void requestSuccess(String result) {
                            Log.i("darren", "createResult:" + result);
                            if (mGameType.equals("1")) {
                                finish();
                            } else {
                                finish();
                                GroupPKCreateActivity.groupPKCreateActivity.finish();
                            }
                        }
                    });
                    asynctask.execute(hashMapCreateUrl, createParams);
                }

            }
        });
        refreshData(1);
    }


    public void refreshData(int page) {
        if (!isLoading) {
            isLoading = true;
            HashMap<String, String> params = new HashMap<>();
            params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
            params.put("enterpriseId", AppConfig.getEnterpriseId());
            params.put("page", page+"");
            params.put("pageSize", HealthyConfig.loadPageCount+"");
            String firendsUrl = "hzlqswserver/health/getFriends";
            HashMap<String, String> hashMapUrl2 = new HashMap<>();
            hashMapUrl2.put("url", firendsUrl);
            MyNoLoadAsynctask asynctask = new MyNoLoadAsynctask(this, new MyNoLoadAsynctask.RequestListener() {
                @Override
                public void requestSuccess(String result) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String res = jsonObject.optString("returnObject");
                        Log.i("darren2", res);
                        HMFriendsDto hmFriendsDto = HMFriendsDto.parserJson(res);
                        List<HMFriend> hmRankList = hmFriendsDto.getData_list();
                        for (int i = 0; i < hmRankList.size(); i++) {
                            HashMap<String, Integer> map = new HashMap<>();
                            map.put("isChoose", 0);
                            map.put("userId", hmRankList.get(i).getUserId());
                            chooseList.add(map);
                        }
                        mAllPersonList.addAll(hmRankList);
                        chooseFriendAdapter.setTotal_data_list(mAllPersonList);
                        chooseFriendAdapter.notifyDataSetChanged();
                        if (hmFriendsDto.getData_list().size() == HealthyConfig.loadPageCount) {
                            isHasMore = true;
                            mPage += 1;
                        } else {
                            isHasMore = false;
                        }
                        chooseFriendAdapter.setIsHasMore(isHasMore);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    isLoading = false;
                }
            });
            asynctask.execute(hashMapUrl2, params);
        }
    }
}
